<template>
  <div>
    <excel
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>

<script>
// 批量导入员工
import { importEmployee } from '@/api/employees'
// 转换时间格式
import { formatExcelDate } from '@/utils/index'
import Excel from './excel.vue'
export default {
  name: '',
  components: { Excel },
  props: {},
  data() {
    return {

    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: '文件太大',
        type: 'warning'
      })
      return false
    },
    // 传入成功之后的回调函数
    async handleSuccess({ results, header }) {
      try {
        const data = this.fromat(results)
        //   console.log('后端需要的格式', data)
        await importEmployee(data)
        this.$message.success('导入成功')
        // 页面后退
        this.$router.back()
      } catch (err) {
        console.log(err)
        this.$message.error('导入失败')
      }
    },
    // 转换格式
    fromat(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      const res = results.map(obj => {
        const newObj = {}
        const zhKeys = Object.keys(obj)
        zhKeys.forEach(zhkey => {
          const enkey = mapInfo[zhkey]
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            newObj[enkey] = new Date(formatExcelDate(obj[zhkey]))
          } else {
            newObj[enkey] = obj[zhkey]
          }
        })
        return newObj
      })
      return res
    }
  }
}
</script>

<style scoped lang='less'>

</style>
